<script>
import { getAction, postAction } from '@api/manage'
import { JVXETypes } from '@comp/jeecg/JVxeTable'

export default {
  name: 'WorkInboundRecordLabelGeneratePrintModal',
  components: { },
  data() {
    return {
      title: '',
      width: 800,
      visible: false,
      disableSubmit: false,
      model: {},
      workshopPlanId: null,
      labelList: [],
      // 批次号数量
      labelNum: 1,
      selectedRecordItemRowKeys: [],
      selectionRecordItemRows: [],
      workInboundRecordItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '计划单号',
            key: 'planNo',
            width: '120px'
          },
          {
            title: '订单编号',
            key: 'orderNo',
            width: '110px'
          },
          {
            title: '物料编码',
            key: 'materialCode',
            width: '110px'
          },
          {
            title: '物料名称',
            key: 'materialName',
            minWidth: '170px'
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            width: '90px'
          },
          {
            title: '配方号',
            key: 'formulaNumber',
            width: '110px'
          },
          {
            title: '单位',
            key: 'unit_dictText',
            dictCode: 'ji_unit',
            width: '60px',
            align: 'center'
          },
          {
            title: '计划数量',
            key: 'planQuantity',
            width: '80px'
          },
          {
            title: '已入库数量',
            key: 'storedQuantity',
            width: '100px'
          },
          {
            title: '打印数量',
            key: 'labelNum',
            type: JVXETypes.inputNumber,
            width: '110px',
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
        ]
      },
      url: {
        workPlan: {
          list: '/wms/inbound/work-inbound-record/listWorkPlans'
        }
      }
    }
  },
  methods: {
    print(record) {
      this.model = Object.assign({}, record)
      this.workshopPlanId = record.id
      this.fetchData()
      this.visible = true
    },
    fetchData() {
      getAction(this.url.workPlan.list, { workshopPlanId: this.workshopPlanId }).then((res) => {
        let { result } = res
        if (result && result.length) {
          this.workInboundRecordItemTable.dataSource = result
        }
      })
    },
    async handleOk() {
      if (!this.selectionRecordItemRows || this.selectionRecordItemRows.length <= 0) {
        this.$message.error('请选择要生成标签的计划')
        return
      }
      const invalidRow = this.selectionRecordItemRows.find(item => {
        const labelNum = item.labelNum
        return labelNum === null || labelNum === undefined || isNaN(labelNum) || labelNum <= 0
      })
      if (invalidRow) {
        this.$message.error('打印数量必须填写且大于0')
        return
      }
      const totalLabelNum = this.selectionRecordItemRows.reduce((sum, item) => {
        const labelNum = item.labelNum
        return !isNaN(labelNum) && labelNum > 0 ? sum + labelNum : sum
      }, 0)
      const { result } = await getAction('/wms/inbound/inbound-order/get-batch-numbers', {
        quantity: totalLabelNum
      })
      if (result) {
        if (result.length < totalLabelNum) {
          this.$message.error('批次号数量不足')
          return
        }
        let batchIndex = 0
        this.labelList = this.selectionRecordItemRows.flatMap(row => {
          const count = parseInt(row.labelNum, 10)
          if (isNaN(count) || count <= 0) return []
          return Array.from({ length: count }, () => ({
            materialCode: row.materialCode,
            materialName: row.materialName,
            specificationModel: row.specificationModel,
            unit: row.unit,
            materialBatchNumber: row.materialBatchNumber,
            quantity: row.quantity,
            planNumber: row.planNo,
            orderNumber: row.orderNo,
            batchNumber: result[batchIndex++]
          }))
        })
        if (!this.labelList || this.labelList.length <= 0) {
          return
        }
        postAction('/wms/inbound/work-inbound-label/save-labels', this.labelList).then((res) => {
          if (res.success) {
            const { result } = res
            if (!result || result.length <= 0) {
              return
            }
            const ids = result.map((item) => item.id).join('\',\'')
            window.open(`${window._CONFIG['domianURL']}/jmreport/view/1099911005488357376?id=${ids}`, '_blank')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
      }
    },
    submitCallback() {
      this.$emit('ok')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.labelList = []
      this.labelNum = 1
      this.$emit('close')
      this.visible = false
    },
    onSelectRecordItemRowChange({ type, action, selectedRows, $event }) {
      this.selectionRecordItemRows = selectedRows
    },
    onClearRecordItemSelected() {
      this.selectedRecordItemRowKeys = []
      this.selectionRecordItemRows = []
    }
  }
}
</script>

<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    fullscreen
    okText="生成标签并打印"
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    cancelText="关闭"
    @cancel="handleCancel">
    <div class="ant-alert ant-alert-info" style="margin: 16px 0;">
      <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
      style="font-weight: 600">{{ selectedRecordItemRowKeys.length }}</a>项
      <a style="margin-left: 24px" @click="onClearRecordItemSelected">清空</a>
    </div>
    <j-vxe-table
      keep-source
      ref="workInboundRecordItem"
      :loading="workInboundRecordItemTable.loading"
      :columns="workInboundRecordItemTable.columns"
      :dataSource="workInboundRecordItemTable.dataSource"
      :maxHeight="300"
      :rowNumber="true"
      :rowSelection="true"
      :toolbar="false"
      @selectRowChange="onSelectRecordItemRowChange"
    ></j-vxe-table>
  </j-modal>
</template>

<style scoped>
</style>